<template>
	<view>
		<view class="content">
			<view class="content_item">
				<view class="content_button" @click="jumpToRecord()">
					打卡记录
				</view>
			</view>
			<view class="content_name">
				<view v-if="classList.name != ''">
					<view class="name">
						<text>{{classList.name}}</text>
					</view>
					<view class="time">
						<text>{{classList.time}}</text>
					</view>
				</view>
				<view v-if="status == '未打卡'">
					<view class="attendance" @click="punch()">
						<text>打卡</text>
					</view>
				</view>
				<view v-else>
					<view style="display: flex; align-items: center; justify-content: center; margin-top: 120rpx;">
						<icon :type="status == '已打卡' ? 'success' : status == '缺勤' ? 'cancel' : 'info'" size="40" style="margin-right: 30rpx;"></icon>
						<view class="status">
							<text>{{status}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="apply" @click="jumpToApply()" v-if="status == '未打卡'">
			<text>发起请假</text>
		</view>
	</view>
</template>

<script>
	import cloudbase from '@cloudbase/js-sdk';
	import dateUtil from '../../util/dateUtil.js';

	const db = cloudbase.database();
	const dbCmd = db.command;
	export default {
		data() {
			return {
				classList: {
					name: '',
					time: ''
				},
				status: '当前没有课程',
				type: '',
				price: ''
			}
		},
		onLoad(param) {
			// 获取当前上课课程，如果不在打卡时间内（上课15分钟内），显示已打卡、已请假、缺勤
			this.getCourses(param);
			this.type = param.type;
			if (param.price == null) {
				this.price = 0;
			} else {
				this.price = param.price;
			}

		},
		methods: {
			// 获取上课课程
			getCourses: function(param) {
				let courseList = JSON.parse(param.studentCourseList);
				// 判断是否处在打卡时间
				this.judgeTime(courseList);
			},
			judgeTime: function(courseList) {
				// 获取当前时间
				let nowTime = new Date();
				courseList.forEach(item => {
					// 获取上课时间
					let classTime = new Date(nowTime.getFullYear() + '-' + (nowTime.getMonth() + 1) + '-' + nowTime.getDate() + ' ' +
						item.time.split('~')[0]);
					// 时间差，单位为分钟
					let diffTime = Math.abs((nowTime.getTime() - classTime.getTime()) / (60 * 1000));
					console.log('classtime:' + classTime);
					console.log('diffTime' + diffTime);
					// 15分钟内可以打卡
					if (diffTime < 15) {
						this.classList.name = item.name;
						this.classList.time = item.time;
						// 判断当前状态
						this.judgeStatus();
						// 退出循环
						return;
					} else if (15 < diffTime && diffTime < 120) {
						this.classList.name = item.name;
						this.classList.time = item.time;
						this.status = '已缺勤';
						return;
					} else {
						this.status = '当前没有课程';
					}
				})
			},
			judgeStatus: function() {
				// 查看打卡数据，判断这节课是否已经打卡
				db.collection('user').where({
					openId: getApp().globalData.userInfo.openId
				}).field({
					attendanceList: true
				}).get().then(res => {
					let attendanceList = res.data[0].attendanceList;
					if (attendanceList == null || this.judgeExist(attendanceList)) {
						this.status = '未打卡';
					} else {
						this.status = '已打卡';
					}
				})
			},
			judgeExist: function(arr) {
				if (arr == null) return true;
				arr.forEach(item => {
					if (item.time == this.formatDate().time) {
						return true;
					}
				})
				return false;
			},
			// 页面跳转
			jumpToSuccess: function() {
				uni.navigateTo({
					url: "../submitSuccess/submitSuccess?index=2"
				})
			},
			jumpToRecord: function() {
				uni.navigateTo({
					url: '../attendRecord/attendRecord'
				})
			},
			jumpToApply: function() {
				uni.navigateTo({
					url: '../apply/apply'
				})
			},
			// 打卡功能
			punch: function() {
				let that = this;
				uni.showLoading({
					title: '打卡中…',
					mask: true
				});
				// 获取打卡地点，打卡时间
				uni.getLocation({
					type: 'wgs84', //默认值
					success: function(res) {
						// 获取用户定位
						let userPoint = new db.Geo.Point(res.longitude, res.latitude);
						// 获取附近机构
						that.getNearInstitution(userPoint);
					}
				})
			},
			getNearInstitution: function(userPoint) {
				// 获取机构的位置
				db.collection('institution').where({
					location: dbCmd.geoNear({
						geometry: userPoint,
						maxDistance: 300,
					})
				}).field({
					_id: true
				}).get().then(res => {
					console.log(res.data);
					console.log(getApp().globalData.userInfo.institutionId);
					// 判断是否在机构附近
					this.clockIn(res.data);
				})
			},
			clockIn: function(institutions) {
				let flag = false;
				institutions.forEach(item => {
					if (item._id == getApp().globalData.userInfo.institutionId) {
						flag = true;
					}
				})
				if (flag) {
					// 修改机构账单
					this.updateBill();
				} else {
					uni.showModal({
						title: '提示',
						content: '当前距离机构位置偏远，请打开定位重试'
					})
				}
			},
			recordInfo: function() {
				db.collection('user').where({
					openId: getApp().globalData.userInfo.openId
				}).update({
					// 记录当前时间和课程名称
					attendanceList: dbCmd.push(this.formatDate())
				}).then(res => {
					console.log(res);
					uni.hideLoading();
				})
			},
			// 修改机构账单
			updateBill: function() {
				let type = this.type;
				// 获取机构信息
				db.collection('institution').where({
					_id: getApp().globalData.userInfo.institutionId
				}).field({
					_openid: true
				}).get().then(res => {
					let _openid = res.data[0]._openid;
					// 记录账单
					this.addBill(_openid);
				})
			},
			// 代码冗余，但是修改麻烦……
			addBill: function(_openid) {
				let today = dateUtil.getFullDate(new Date());
				let date = dateUtil.getToDay(new Date());
				let flag = false;
				let type = this.type;
				let price = this.price;
				let billItem = {
					price: type == '学生' ? (price * 100) / 100 : ~((price * 100) / 100 - 1),
					costType: {
						icon: '../../static/orther_income.png',
						name: type == '学生' ? '课程收入' : '老师课酬',
						type: 3
					},
					billType: type == '学生' ? 'income' : 'spendding',
					note: type + '-' + getApp().globalData.userInfo.realName + '打卡',
				}
				// 获取月账单
				db.collection('user').where({
					_openid
				}).field({
					"billList": true
				}).get().then(res => {
					let billList;
					if (res.data[0].billList) {
						if (res.data[0].billList[today[0]]) {
							if (res.data[0].billList[today[0]][today[1]]) {
								billList = res.data[0].billList[today[0]][today[1]].bill;
								// console.log(billList); 
								for (let i = 0; i < billList.length; i++) {
									if (billList[i].date == today) {
										// 在这一天追加内容，并退出循环
										billList[i].bill.push(billItem);
										billList[i].spendding += type == '学生' ? (price * 100) / 100 : 0;
										billList[i].income += type == '教师' ? (price * 100) / 100 : 0;
										flag = true;
										break;
									}
								}
							}
						}
					}
					if (flag) {
						// 覆盖原来的月账单
						db.collection('user').where({
							_openid
						}).update({
							billList: {
								[today[0]]: {
									income: dbCmd.inc(type == '学生' ? (price * 100) / 100 : 0),
									spendding: dbCmd.inc(type == '教师' ? (price * 100) / 100 : 0),
									[today[1]]: {
										income: {
											price: dbCmd.inc(type == '学生' ? (price * 100) / 100 : 0),
											[billItem.costType.name]: dbCmd.inc(type == '学生' ? (price * 100) / 100 : 0)
										},
										spendding: {
											price: dbCmd.inc(billType == 'spendding' ? (price * 100) / 100 : 0),
											[billItem.costType.name]: dbCmd.inc(type == '教师' ? (price * 100) / 100 : 0)
										},
										bill: billList
									}
								}
							}
						}).then(res => {
							console.log(res);
							if (res.updated != 0) {
								// 打卡成功
								this.jumpToSuccess();
								this.recordInfo();
							}
						})
					} else {
						// 新增账单
						db.collection('user').where({
							_openid
						}).update({
							billList: {
								[today[0]]: {
									date: today[0],
									income: dbCmd.inc(type == '学生' ? (price * 100) / 100 : 0),
									spendding: dbCmd.inc(type == '教师' ? (price * 100) / 100 : 0),
									[today[1]]: {
										date: today[0] + today[1],
										income: {
											price: dbCmd.inc(type == '学生' ? (price * 100) / 100 : 0),
											[billItem.costType.name]: dbCmd.inc(type == '学生' ? (price * 100) / 100 : 0)
										},
										spendding: {
											price: dbCmd.inc(type == '教师' ? (price * 100) / 100 : 0),
											[billItem.costType.name]: dbCmd.inc(type == '教师' ? (price * 100) / 100 : 0)
										},
										bill: dbCmd.push({
											date: date,
											sort: new Date(dateUtil.toDate(date)).getTime(),
											income: type == '学生' ? (price * 100) / 100 : 0,
											spendding: type == '教师' ? (price * 100) / 100 : 0,
											bill: [billItem]
										})
									}
								}
							}
						}).then(res => {
							console.log(res);
							if (res.updated != 0) {
								this.jumpToSuccess();
								this.recordInfo();
								// 对数据内容进行排序
								db.collection('institution').where({
									_openid
								}).update({
									billList: {
										[today[0]]: {
											[today[1]]: {
												bill: dbCmd.push({
													each: [],
													sort: {
														sort: -1
													}
												})
											}
										}
									}
								})
							}
						})
					}
				})
			},
			formatDate: function() {
				let nowDate = new Date();
				let attendance = {
					time: nowDate.getFullYear() + '年' + (nowDate.getMonth() + 1) + '月' + nowDate.getDate() + '日 ' + this.classList.time,
					class: this.classList.name,
					status: '已打卡',
					institution: getApp().globalData.userInfo.institution
				}
				return attendance;
			}
		}
	}
</script>

<style>
	page {
		/* width: 750rpx; */
		/* height: 1020rpx; */
		/* padding-bottom: 60px; */
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background-color: #F3F5F7;
	}

	.content {
		width: 702rpx;
		height: 607rpx;
		margin-top: 24rpx;
		margin-left: auto;
		margin-right: auto;
		background-color: #FFFFFF;
		border-radius: 32rpx;
	}

	.content_item {
		width: 702rpx;
		height: 70rpx;
	}

	.content_button {

		width: 200rpx;
		height: 70rpx;
		margin-top: 18rpx;
		margin-left: 480rpx;
		background-color: #FFECDC;
		border-radius: 32rpx;
		line-height: 70rpx;
		font-size: 35rpx;
		color: #FD973F;
		text-align: center;
	}

	.content_name {
		width: 702rpx;
		height: 119rpx;
		text-align: center;
	}

	.name {
		font-size: 50rpx;
		line-height: 70rpx;
		color: #666666;
	}

	.time {
		font-size: 35rpx;
		line-height: 49rpx;
		color: #666666;
	}

	.attendance {
		width: 258rpx;
		height: 258rpx;
		margin-top: 39rpx;
		margin-right: auto;
		margin-left: auto;
		border-radius: 50%;
		background-color: #FD973F;
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
		color: #FFFFFF;
		text-align: center;
		line-height: 258rpx;
		font-size: 50rpx;
	}

	.apply {
		width: 702rpx;
		height: 167rpx;
		margin-left: auto;
		margin-right: auto;
		margin-top: 42rpx;
		background-color: #FD973F;
		border-radius: 32rpx;
		text-align: center;
		line-height: 167rpx;
		color: #FFFFFF;
		font-size: 45rpx;
	}

	.status {
		color: #FD973F;
		/* width: 100%; */
		/* margin-top: 150rpx; */
		font-size: 50rpx;
		text-align: center;
	}
</style>
